package com.lcxsoft.msmservice.controller;


import com.lcxsoft.commonutils.R;
import com.lcxsoft.msmservice.service.MsmService;
import com.lcxsoft.msmservice.url.MsmServiceUrl;
import com.lcxsoft.msmservice.utils.RandomUtil;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping(MsmServiceUrl.packageUrl)
@CrossOrigin
public class MsmController {

    @Resource
    private MsmService msmService;

    @Resource
    private RedisTemplate<String, String> redisTemplate;

    //发送短信的方法
    @RequestMapping(value = MsmServiceUrl.Msm.send, method = RequestMethod.POST)
    public R sendMsm(String phone) throws Exception {
        //从redis获取验证码。如果获取到直接返回
        String codeFromRedis = redisTemplate.opsForValue().get(phone);
        if (!StringUtils.isEmpty(codeFromRedis)){
            return R.ok();
        }
        //如果redis获取不到进行发送验证码
        String code = RandomUtil.getFourBitRandom();
        Map<String, Object> param = new HashMap<>();
        param.put("code", code);
        boolean isSend = msmService.sendAlibaba(param, phone);
        if (isSend){
            //获取到的验证码保存到redis中存5分钟
            redisTemplate.opsForValue().set(phone, code, 5, TimeUnit.MINUTES);
            return R.ok();
        }
        return R.error().message("短信发送失败");
    }
}
